package com.qing.picture.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qing.picture.exception.BusinessException;
import com.qing.picture.exception.ErrorCode;
import com.qing.picture.exception.ThrowUtils;
import com.qing.picture.mapper.SpaceUserMapper;
import com.qing.picture.model.dto.spaceUser.SpaceUserAddRequest;
import com.qing.picture.model.dto.spaceUser.SpaceUserQueryRequest;
import com.qing.picture.model.entity.Space;
import com.qing.picture.model.entity.SpaceUser;
import com.qing.picture.model.entity.User;
import com.qing.picture.model.enums.SpaceRoleEnum;
import com.qing.picture.model.vo.SpaceUserVo;
import com.qing.picture.model.vo.SpaceVo;
import com.qing.picture.model.vo.UserVo;
import com.qing.picture.service.SpaceService;
import com.qing.picture.service.SpaceUserService;
import com.qing.picture.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 86157
* @description 针对表【space_user(空间用户关联)】的数据库操作Service实现
* @createDate 2025-04-11 08:36:39
*/
@Service
public class SpaceUserServiceImpl extends ServiceImpl<SpaceUserMapper, SpaceUser>
    implements SpaceUserService{

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    /**
     * 新增空间用户
     * @param spaceUserAddRequest
     * @return
     */
    @Override
    public Long addSpaceUser(SpaceUserAddRequest spaceUserAddRequest) {
        ThrowUtils.throwIf(spaceUserAddRequest == null, ErrorCode.PARAMS_ERROR);
        SpaceUser spaceUser = new SpaceUser();
        BeanUtils.copyProperties(spaceUserAddRequest, spaceUser);

        spaceUser.setCreateTime(new Date());
        spaceUser.setUpdateTime(new Date());

        // 校验参数
        this.validSpaceUser(spaceUser, true);

        // 保存
        boolean result = this.save(spaceUser);
        ThrowUtils.throwIf(!result, ErrorCode.SAVE_ERROR);
        return spaceUser.getId();
    }

    /**
     * 转换为 VO 对象
     * @param spaceUser
     * @param request
     * @return
     */
    @Override
    public SpaceUserVo getSpaceUserVo(SpaceUser spaceUser, HttpServletRequest request) {
        SpaceUserVo spaceUserVo = SpaceUserVo.objToVo(spaceUser);
        // 关联查询用户信息
        Long userId = spaceUser.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVo userVO = userService.getUserVO(user);
            spaceUserVo.setUserVo(userVO);
        }
        // 关联查询空间信息
        Long spaceId = spaceUser.getSpaceId();
        if (spaceId != null && spaceId > 0) {
            Space space = spaceService.getById(spaceId);
            SpaceVo spaceVO = spaceService.getSpaceVo(space, request);
            spaceUserVo.setSpaceVo(spaceVO);
        }
        return spaceUserVo;
    }

    @Override
    public List<SpaceUserVo> getSpaceUserVOList(List<SpaceUser> spaceUserList) {
        if(ObjUtil.isEmpty(spaceUserList)){
            return Collections.emptyList();
        }

        // 转换为 VO 对象
        List<SpaceUserVo> spaceUserVoList = spaceUserList.stream().map(SpaceUserVo::objToVo).collect(Collectors.toList());

       //收集用户ID
        Set<Long> userIdSet = spaceUserList.stream().map(SpaceUser::getUserId).collect(Collectors.toSet());
        //收集空间ID
        Set<Long> spaceIdSet = spaceUserList.stream().map(SpaceUser::getSpaceId).collect(Collectors.toSet());

        // 关联查询用户信息
        List<User> userList = userService.listByIds(userIdSet);
        Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, user -> user));
        // 关联查询空间信息
        List<Space> spaceList = spaceService.listByIds(spaceIdSet);
        Map<Long, Space> spaceMap = spaceList.stream().collect(Collectors.toMap(Space::getId, space -> space));


        // 关联查询用户信息
        for (SpaceUserVo spaceUserVo : spaceUserVoList) {
            Long userId = spaceUserVo.getUserId();
            if (userId != null && userId > 0) {
                User user = userMap.get(userId);
                UserVo userVO = userService.getUserVO(user);
                spaceUserVo.setUserVo(userVO);
            }
            Long spaceId = spaceUserVo.getSpaceId();
            if (spaceId != null && spaceId > 0) {
                Space space = spaceMap.get(spaceId);
                SpaceVo spaceVO = spaceService.getSpaceVo(space, null);
                spaceUserVo.setSpaceVo(spaceVO);
            }
        }

        return spaceUserVoList;
    }

    /**
     * 根据条件查询空间用户
     * @param spaceUserQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<SpaceUser> getQueryWrapper(SpaceUserQueryRequest spaceUserQueryRequest) {
        QueryWrapper<SpaceUser> queryWrapper = new QueryWrapper<>();
        if (spaceUserQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = spaceUserQueryRequest.getId();
        Long spaceId = spaceUserQueryRequest.getSpaceId();
        Long userId = spaceUserQueryRequest.getUserId();
        String spaceRole = spaceUserQueryRequest.getSpaceRole();
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceRole), "spaceRole", spaceRole);
        return queryWrapper;
    }

    /**
     * 校验空间用户
     * @param spaceUser
     * @param add
     */
    @Override
    public void validSpaceUser(SpaceUser spaceUser,boolean add) {
        ThrowUtils.throwIf(spaceUser == null, ErrorCode.PARAMS_ERROR);
        // 创建时，空间 id 和用户 id 必填
        Long spaceId = spaceUser.getSpaceId();
        Long userId = spaceUser.getUserId();
        if (add) {
            ThrowUtils.throwIf(ObjectUtil.hasEmpty(spaceId, userId), ErrorCode.PARAMS_ERROR);
            User user = userService.getById(userId);
            ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
        // 校验空间角色
        String spaceRole = spaceUser.getSpaceRole();
        SpaceRoleEnum spaceRoleEnum = SpaceRoleEnum.getByValue(spaceRole);
        if (spaceRole != null && spaceRoleEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间角色不存在");
        }
    }
}




